<?php

namespace App\Http\Controllers\Seller;

use App\Http\Requests\Seller\Finance\CreateRequest;
use App\Models\Finance;
use App\Repositories\Seller\FinanceRepository;
use Illuminate\Http\Request;

class FinanceController extends BaseController
{
    //
    public function __construct()
    {
        $this->repo = new FinanceRepository();
    }

    public function fetchList(Request $request)
    {
        $where = [];
        $where['seller_id'] = $this->id();
        $params = $request->all();
        $is_income = $request->get('is_income',-1);
        if($is_income>-1){
            $where['is_income'] = $is_income;
        }
        $type = $request->get('type',-1);
        if($type>-1){
            $where['type'] = $type;
        }
        $dateRange = $request->get('dateRange',[]);
        if($dateRange){
            $where[] = ['created_at','>=',$dateRange[0]];
            $where[] = ['created_at','<=',$dateRange[1]];

        }
        $page = $this->repo->pagination($where, $params);
        $data = $page->toArray();
        $data['flow'] = $this->repo->sum($where);
        $data['income'] = $this->repo->sum($where,'income');
        $data['expend'] = $this->repo->sum($where,'expend');
        return $this->success($data);
    }
    public function fetchType(){
        return $this->success(array_values(Finance::$mapExpendType));
    }
    public function create(CreateRequest $request)
    {
        $seller_id = $this->id();
        $money = $request->get('money');
        $desc = $request->get('desc','');
        $type = $request->get('type');
        $generated_at = $request->get('generated_at',now());
        $finance = FinanceRepository::add($seller_id, $money, $desc, $type,$generated_at);
        return $finance ? $this->success($finance, '添加成功') : $this->error('添加失败');
    }
    public function delete(Finance $finance){
        $seller_id = $this->id();
        if($finance->seller_id !=$seller_id){
            return $this->error('记录不存在',[],404,404);
        }
        $finance->delete();
        return $this->success([],'删除成功');
    }
}
